<!-- 用户认证组件 - 开发者：彭鸿润 -->
<template>
  <div v-if="!isLoggedIn" class="auth-container">
    <div class="auth-form">
      <h2>{{ isLogin ? '登录' : '注册' }}</h2>
      <input 
        v-model="username" 
        type="text" 
        placeholder="用户名"
        @keydown.enter="handleSubmit"
      >
      <input 
        v-model="password" 
        type="password" 
        placeholder="密码"
        @keydown.enter="handleSubmit"
      >
      <button @click="handleSubmit">
        {{ isLogin ? '登录' : '注册' }}
      </button>
      <button @click="toggleMode" class="toggle-btn">
        {{ isLogin ? '切换到注册' : '切换到登录' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const emit = defineEmits(['login-success']);

const isLoggedIn = ref(false);
const isLogin = ref(true);
const username = ref('');
const password = ref('');

const toggleMode = () => {
  isLogin.value = !isLogin.value;
};

const handleSubmit = () => {
  if (!username.value.trim() || !password.value.trim()) {
    alert('请输入用户名和密码');
    return;
  }

  if (isLogin.value) {
    // 登录逻辑
    const users = JSON.parse(localStorage.getItem('users') || '[]');
    const user = users.find(u => u.username === username.value && u.password === password.value);
    if (user) {
      isLoggedIn.value = true;
      emit('login-success', username.value);
    } else {
      alert('用户名或密码错误');
    }
  } else {
    // 注册逻辑
    const users = JSON.parse(localStorage.getItem('users') || '[]');
    if (users.find(u => u.username === username.value)) {
      alert('用户名已存在');
      return;
    }
    users.push({ username: username.value, password: password.value });
    localStorage.setItem('users', JSON.stringify(users));
    alert('注册成功，请登录');
    isLogin.value = true;
  }
};
</script>

<style scoped>
/* 认证组件样式 */
.auth-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.auth-form {
  background: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  width: 300px;
}

.auth-form h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #25b99a;
}

.auth-form input {
  width: 100%;
  padding: 12px;
  margin-bottom: 15px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
  box-sizing: border-box;
}

.auth-form button {
  width: 100%;
  padding: 12px;
  background: #25b99a;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 14px;
  cursor: pointer;
  margin-bottom: 10px;
}

.auth-form button:hover {
  background: #1e9b7d;
}

.toggle-btn {
  background: #6c757d !important;
}

.toggle-btn:hover {
  background: #5a6268 !important;
}
</style>
